package cn.kow.kmall.controller.item;

import cn.kow.kmall.pojo.dto.CategoryQueryDTO;
import cn.kow.kmall.admin.pojo.vo.CategoryVO;
import cn.kow.kmall.controller.BaseController;
import cn.kow.kmall.core.response.KmallResult;
import cn.kow.kmall.pojo.entity.ItemCategory;
import cn.kow.kmall.service.ItemCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-05-13 15:27
 * @Modified By:
 */
@Slf4j
@RestController
@RequestMapping("/item/category")
public class ItemCategoryController extends BaseController {

    /**
     * 分类服务
     */
    @Autowired
    private ItemCategoryService categoryService;

    /**
     * 新增类目
     * @param category  类目
     * @return 结果
     */
    @PostMapping(value = "/add")
    public KmallResult add(@Validated @RequestBody ItemCategory category) {
        String userName = currentUser().getUsername();
        category.setCreateBy(userName);
        category.setUpdateBy(userName);
        categoryService.save(category);
        return KmallResult.success();
    }

    @PostMapping("/del")
    public KmallResult remove(@RequestBody Long[] ids) {
        categoryService.remove(Arrays.asList(ids));
        return KmallResult.success();
    }

    @PostMapping(value = "/edit")
    public KmallResult edit(@Validated @RequestBody ItemCategory category) {
        String userName = currentUser().getUsername();
        category.setUpdateBy(userName);
        categoryService.update(category);
        return KmallResult.success();
    }

    @PostMapping(value = "/list")
    public KmallResult list(@RequestBody CategoryQueryDTO queryDTO) {
        // 所有的一级类目
        List<ItemCategory> superCategoryList = categoryService.listByParentId(0L);
        List<CategoryVO> categoryList = new ArrayList<>();
        for(ItemCategory category : superCategoryList) {
            CategoryVO categoryVO = toVO(category);
            List<ItemCategory> subList = categoryService.listByParentId(category.getId());
            categoryVO.setChildren(subList.stream().map(a -> toVO(a)).collect(Collectors.toList()));
            categoryList.add(categoryVO);
        }
        return KmallResult.success().put("rows", categoryList);
    }

    private CategoryVO toVO(ItemCategory category) {
        CategoryVO vo = new CategoryVO();
        BeanUtils.copyProperties(category, vo);
        return vo;
    }

    /**
     * 获取类目详情
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}")
    public KmallResult info(@PathVariable Long id) {
        ItemCategory category = categoryService.getById(id);
        return KmallResult.success(category);
    }
}
